package com.example.pay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.authority.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/pay")
@Slf4j
public class PayController {

    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private AliPayConfig aliPayConfig;
    @GetMapping("alipay")
    public void alipay(Integer orderId, HttpServletResponse response) throws
            IOException {
        //这里与鉴权系统集成，获取当前用户的id
        String currentUserId = String.valueOf(SecurityUtils.getCurrentUser().getUser().getId());
        // 实例化客户端,填入所需参数
        AlipayTradePagePayRequest request = new
                AlipayTradePagePayRequest();
        // 在公共参数中设置回跳和通知地址
        request.setReturnUrl(aliPayConfig.getRETURN_URL());

        //request.setNotifyUrl(aliPayConfig.getNOTIFY_URL());
        // TODO： 根据订单编号,查询订单相关信息（要自己修改）
//        OrderDetailVo order = ordersMapper.selectDetailById(orderId,
//                currentUserId);

        // 商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderId.toString();
        // 付款金额，必填
        String total_amount = "0.01";
        // 订单名称，必填
        String subject = "熙心健康体检";
        // 商品描述，可空
        String body = "冰丝内裤";
        request.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
            log.info(form);
        } catch (AlipayApiException e) {
            log.error("支付宝调用异常", e);
        }
        response.setContentType("text/html;charset=" +
                aliPayConfig.getCHARSET());
        response.getWriter().write(form);// 直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }
    @GetMapping(value = "/notifyUrl")
    public void notifyUrl(){
        System.out.println("notifyUrl");
    }
    @GetMapping(value = "/returnUrl")
    public void returnUrl(HttpServletRequest request, HttpServletResponse
            response)
            throws IOException, AlipayApiException {
        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr +
                        values[i] + ",";
            }
            // 解决乱码
            valueStr = new String(valueStr.getBytes(StandardCharsets.UTF_8),
                    StandardCharsets.UTF_8);
            params.put(name, valueStr);
        }

        System.out.println(params);// 查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                aliPayConfig.getALIPAY_PUBLIC_KEY(), aliPayConfig.getCHARSET(),
                aliPayConfig.getSIGN_TYPE()); // 调用SDK验证签名
        // 验证签名通过
        if(signVerified){
            // 商户订单号，这个后面用来确定到底要修改哪一个订单
            String out_trade_no = new
                    String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

            // 支付宝交易号
            String trade_no = new
                    String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

            // 付款金额
            String total_amount = new
                    String(request.getParameter("total_amount").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

            System.out.println("商户订单号 = " + out_trade_no);
            System.out.println("支付宝交易号 = " + trade_no);
            System.out.println("付款金额 = " + total_amount);

            // 支付成功，修改支付状态
            //这个在我们那个项目应该是：paycode
            //TODO：自己完成order表当中的pay_type, pay_code, pay_time, state字段的更新
            response.sendRedirect("http://localhost:5173/appointmentSuccess");
        }else{
            //不成功，订单状态将是未支付
            response.sendRedirect("http://localhost:5173/appointmentFail");
        }
    }
}
